package com.selenium.service;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.selenium.Config;
import com.selenium.CookieUtils;
import com.worktool.RestExecutor;
import org.apache.commons.lang3.StringUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class OpServiceImp implements OpService{

    public enum OnOff{
        START("已启用"),END("未启用");

        private String title;

        OnOff(String title) {
            this.title = title;
        }

        public static String getTitle(int index){
            OnOff[] OnOffs = OnOff.values();
            return OnOffs[index].title;
        }

    }

    private static List<String> cookie;

    private static RestTemplate restTemplate = RestExecutor.build();

    public OpServiceImp(List<String> cookie){
        this.cookie = cookie;
    }


    /**
     * 关闭微信插件 - 在微信插件底部可快捷打开企业微信客户端
     * @param state 1:开启；2关闭
     */
    @Override
    public void wxpluginSetShowBanner(Integer state,String describe) {
        String url = "https://work.weixin.qq.com/wework_admin/wxplugin/setShowBanner?" +
                "lang=zh_CN&f=json&ajax=1&timeZoneInfo%5Bzone_offset%5D=-8&random="+Math.random();

//        Map<String,Object> params = new HashMap<>();
//        params.put("state",2);
//        params.put("_d2st","a5990576");

        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
        params.add("state", "2");
//        params.add("_d2st", "a5990576");

        HttpHeaders httpHeaders = new HttpHeaders();

        httpHeaders.put(HttpHeaders.COOKIE, cookie);
        httpHeaders.set("content-type","application/x-www-form-urlencoded");
        httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        httpHeaders.add("Referer","https://work.weixin.qq.com/wework_admin/frame");

        HttpEntity requestEntity = new HttpEntity<>(params, httpHeaders);

        JSONObject json = restTemplate.postForObject(url,requestEntity,JSONObject.class);
        this.print(json,describe);

    }

    /**
     * 关闭微信插件 - 成员使用微信插件时需要使用企业微信客户端
     */
    @Override
    public void setWxPluginInfo(String describe) {
        String url = "https://work.weixin.qq.com/wework_admin/wxplugin/setWxPluginInfo?lang=zh_CN&f=json&ajax=1&timeZoneInfo%5Bzone_offset%5D=-8&random="+Math.random();

//        Map<String,Object> params = new HashMap<>();
//        params.put("state",2);
//        params.put("_d2st","a5990576");

        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
        params.add("block_message_in_wxplugin", false);

        HttpHeaders httpHeaders = new HttpHeaders();

        httpHeaders.put(HttpHeaders.COOKIE, cookie);
        httpHeaders.set("content-type","application/x-www-form-urlencoded");
        httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        httpHeaders.add("Referer","https://work.weixin.qq.com/wework_admin/frame");

        HttpEntity requestEntity = new HttpEntity<>(params, httpHeaders);

        JSONObject json = restTemplate.postForObject(url,requestEntity,JSONObject.class);

        this.print(json,describe);

    }

    /**
     * 关闭邮件
     */
    @Override
    public void setBizClosed(String describe, WebDriver driver, int status) {
//        String url = "https://exmail.qq.com/qy_mng_logic/wework/setBizClosed?" +
//                "sid=xjc8o7PdqlSu4S9L,7&lang=zh_CN&ajax=1&f=json&random="+Math.random();
//
//
//        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
//        params.add("state", "1");
//
//        HttpHeaders httpHeaders = new HttpHeaders();
//
//        httpHeaders.put(HttpHeaders.COOKIE, cookie);
//        httpHeaders.set("content-type","application/x-www-form-urlencoded");
//        httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
////        httpHeaders.add("Referer","https://work.weixin.qq.com/wework_admin/frame");
//        httpHeaders.add("Referer","https://exmail.qq.com/qy_mng_logic/wework/frame?sid=xjc8o7PdqlSu4S9L,7");
//
//        HttpEntity requestEntity = new HttpEntity<>(params, httpHeaders);
//
//        JSONObject json = restTemplate.postForObject(url,requestEntity,JSONObject.class);

//        this.print(json,describe);

        this.goXz(driver);


        CookieUtils.wait(driver,By.xpath("//a[(@href='#apps/qykit/proxy/exmail')]")).click();//邮件
//        CookieUtils.wait(driver,By.xpath("/html/body/div[3]/div[1]/div[1]/div/a[1]")).click();//邮件
        CookieUtils.wait(driver,By.xpath("//a[(@href='#apps/qykit/proxy/exmail')]")).click();//邮件

        this.waitByMi(3000);

        String opStr = OnOff.getTitle(status);

        System.err.println(opStr+":邮件");

        //div[@class="qykit_container js_qykitItem" and @data-type='exmail']/iframe

        WebElement ifram =CookieUtils.wait(driver,By.xpath("//div[@class='qykit_container js_qykitItem' and @data-type='exmail']/iframe"));

        driver.switchTo().frame(ifram);


        WebElement statusEle = CookieUtils.wait(driver,By.className("index_header_left_content_header_status"));

        if(opStr.equals(statusEle.getText())){
            driver.switchTo().defaultContent();
            System.err.println("状态一致退出");
            return;
        }

        WebElement onoffele = CookieUtils.wait(driver,By.xpath("//*[@id=\"js_ww_new_index\"]/div[1]/div[1]/div/div[2]/div[1]/div[2]"));

        onoffele.click();
        driver.switchTo().defaultContent();

        if(OnOff.END.ordinal() == status){


            WebElement iframAlert =CookieUtils.wait(driver,By.xpath("//div[@class='qykit_container js_qykitItem' and @data-type='exmail']/div[2]/iframe"));

            driver.switchTo().frame(iframAlert);

            WebElement stopAlert = CookieUtils.wait(driver,By.xpath("//*[@id=\"_pANelmAsk_\"]/div/div/div/div[1]/div/div/div[2]/a[1]"));
            stopAlert.click();
        }

        driver.switchTo().defaultContent();

        System.err.println(opStr+":成功");


    }

    private void waitByMi(long mi){
        try {
            Thread.sleep(mi);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


    /**
     * 文档-要破解
     *
     */
    @Override
    public void mngcorpsetting(String describe, WebDriver driver,int status) {

        this.goXz(driver);


        CookieUtils.wait(driver,By.xpath("//a[(@href='#apps/qykit/proxy/wedoc')]")).click();//文档


        String opStr = OnOff.getTitle(status);

        System.err.println(opStr+":文档");

        WebElement ifram =CookieUtils.wait(driver,By.xpath("//div[@class='qykit_container js_qykitItem' and @data-type='wedoc']/iframe"));

        driver.switchTo().frame(ifram);


        WebElement statusEle = CookieUtils.wait(driver,By.className("iframeHome_header_open_label"));

        if(opStr.equals(statusEle.getText())){
            driver.switchTo().defaultContent();
            System.err.println("状态一致退出");
            return;
        }


        WebElement onoffele = CookieUtils.wait(driver,By.xpath("//i[@class='iframeHome_header_open_switch_core xd_admin_SwitchBT']"));
        onoffele.click();

        driver.switchTo().defaultContent();

        if(OnOff.END.ordinal() == status){
            WebElement stopAlert = CookieUtils.wait(driver,By.xpath("//a[@class='qui_btn ww_btn ww_btn_Blue' and @node-type='ok' and @href='javascript:;']"));
            stopAlert.click();
        }

        ///html/body/div[4]/div/div[3]/a[1]
        //a[@class='qui_btn ww_btn ww_btn_Blue' and @node-type='ok']

        System.err.println(opStr+":成功");

    }

    /**
     * 关闭成员
     */
    @Override
    public void closeMember(String describe) {
        String url = "https://work.weixin.qq.com/wework_admin/auto_invite/setting/change?" +
                "lang=zh_CN&f=json&ajax=1&timeZoneInfo%5Bzone_offset%5D=-8&random="+Math.random();

//        Map<String,Object> params = new HashMap<>();
//        params.put("state",2);
//        params.put("_d2st","a5990576");

        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
        params.add("enable", "0");
        params.add("from", "memberjoin");

        HttpHeaders httpHeaders = new HttpHeaders();

        httpHeaders.put(HttpHeaders.COOKIE, cookie);
        httpHeaders.set("content-type","application/x-www-form-urlencoded");
        httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        httpHeaders.add("Referer","https://work.weixin.qq.com/wework_admin/frame");

        HttpEntity requestEntity = new HttpEntity<>(params, httpHeaders);

        JSONObject json = restTemplate.postForObject(url,requestEntity,JSONObject.class);
        this.print(json,describe);

    }



    /**
     * 关闭日程/会议
     * @param business_id 10084/10085
     */
    @Override
    public void ModifyCorpApplication(String business_id,String describe) {
        String url = "https://work.weixin.qq.com/wework_admin/ModifyCorpApplication?lang=zh_CN&f=json&ajax=1&timeZoneInfo%5Bzone_offset%5D=-8&random=0.8959054577734176";

        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();

        params.add("app_type", "1");
        params.add("open_state", "0");

        params.add("business_id", business_id);

        HttpHeaders httpHeaders = new HttpHeaders();

        httpHeaders.put(HttpHeaders.COOKIE, cookie);
        //httpHeaders.set("content-type","application/x-www-form-urlencoded");
        httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
//        httpHeaders.add("Referer","https://work.weixin.qq.com/wework_admin/frame");
        httpHeaders.add("Referer","https://work.weixin.qq.com/wework_admin/frame");

        HttpEntity requestEntity = new HttpEntity<>(params, httpHeaders);

        JSONObject json = restTemplate.postForObject(url,requestEntity,JSONObject.class);
        this.print(json,describe);

    }

    /**
     * 关闭聊天
     */
    @Override
    public void room(String describe) {
        String url = "https://work.weixin.qq.com/wework_admin/profile/room?lang=zh_CN&f=json&ajax=1&timeZoneInfo%5Bzone_offset%5D=-8&random=0.10480860751960552";

        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
        params.add("type", "total");
        params.add("data", "{\"leaderlist\":[],\"bigroomwhitelist\":{\"bigroomsize\":200},\"newbigroomwhitelist\":[],\"messagestoragewhitelist\":[],\"corp_room_open\":false,\"room_limit\":2000,\"room_open\":false,\"room_limit_options\":[2000,10000]}");
        params.add("save_time", "0");
        params.add("corp_room_open", false);
        params.add("room_open", false);

        HttpHeaders httpHeaders = new HttpHeaders();

        httpHeaders.put(HttpHeaders.COOKIE, cookie);
        //httpHeaders.set("content-type","application/x-www-form-urlencoded");
        httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
//        httpHeaders.add("Referer","https://work.weixin.qq.com/wework_admin/frame");
        httpHeaders.add("Referer","https://work.weixin.qq.com/wework_admin/frame");

        HttpEntity requestEntity = new HttpEntity<>(params, httpHeaders);

        JSONObject json = restTemplate.postForObject(url,requestEntity,JSONObject.class);
        this.print(json,describe);

    }

    /**
     * 关闭工作台
     */
    @Override
    public void settings(String describe) {
        String url = "https://work.weixin.qq.com/wework_admin/profile/workbench/settings?lang=zh_CN&f=json&ajax=1&timeZoneInfo%5Bzone_offset%5D=-8&random=0.11316577900224312";

        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();

        params.add("b_show_appstore_to_everyone", false);
        params.add("b_is_corp_chain_gray", true);
        params.add("b2b_app_member_hide_int", "1");
        params.add("b_show_reserveservice_to_everyone", false);

        HttpHeaders httpHeaders = new HttpHeaders();

        httpHeaders.put(HttpHeaders.COOKIE, cookie);
        //httpHeaders.set("content-type","application/x-www-form-urlencoded");
        httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
//        httpHeaders.add("Referer","https://work.weixin.qq.com/wework_admin/frame");
        httpHeaders.add("Referer","https://work.weixin.qq.com/wework_admin/frame");

        HttpEntity requestEntity = new HttpEntity<>(params, httpHeaders);

        JSONObject json = restTemplate.postForObject(url,requestEntity,JSONObject.class);
        this.print(json,describe);

    }

    /**
     * 微盘 - 要破解
     */
    @Override
    public void updatecorpinfo(String describe, WebDriver driver,int status) {
//        String url = "https://drive.weixin.qq.com/diskmng/updatecorpinfo?sid=AX5EVQAZaWsG5nZvANJBVwAA&r=97579065656471694154394679";
//
//        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
//        params.add("func", "3");
//        params.add("corp_id", "");
////        params.add("business_id", "10084");
//        params.add("vid", "");
//        params.add("app_open", false);
//        params.add("corpid", "");
//
//
//        System.out.println("params----------"+params);
//
//        HttpHeaders httpHeaders = new HttpHeaders();
//
//        System.err.println(cookie);
//        httpHeaders.put(HttpHeaders.COOKIE, cookie);
//        //httpHeaders.set("content-type","application/x-www-form-urlencoded");
//        httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
////        httpHeaders.add("Referer","https://work.weixin.qq.com/wework_admin/frame");
//        httpHeaders.add("Referer","https://exmail.qq.com/qy_mng_logic/wework/frame?sid=xjc8o7PdqlSu4S9L,7");
//
//        HttpEntity requestEntity = new HttpEntity<>(params, httpHeaders);
//
//        JSONObject json = restTemplate.postForObject(url,requestEntity,JSONObject.class);
//        if(json.containsKey("data")){
//            System.err.println("weipan：关闭打开企业微信成功");
//        }
//        System.err.println(json);

        this.goXz(driver);

        CookieUtils.wait(driver,By.xpath("//a[(@href='#apps/qykit/proxy/wedrive')]")).click();//微盘

        String opStr = OnOff.getTitle(status);

        System.err.println(opStr+":微盘");

        WebElement ifram =CookieUtils.wait(driver,By.xpath("//div[@class='qykit_container js_qykitItem' and @data-type='wedrive']/iframe"));

        driver.switchTo().frame(ifram);

        WebElement statusEle = CookieUtils.wait(driver,By.className("iframeHome_header_open_label"));

        if(opStr.equals(statusEle.getText())){
            System.err.println("状态一致退出");
            return;
        }


        WebElement onoffele = CookieUtils.wait(driver,By.xpath("//i[@class='iframeHome_header_open_switch_core xd_admin_SwitchBT']"));

        //WebElement onoffele = CookieUtils.wait(driver,By.xpath("//*[@id=\"wedriveIframeContainer\"]/section/section/main/div/div/div[1]/div[1]/div[2]/div[1]/div/span"));
        onoffele.click();

        driver.switchTo().defaultContent();

        if(OnOff.END.ordinal() == status){
            WebElement stopAlert = CookieUtils.wait(driver,By.xpath("//a[@class='qui_btn ww_btn ww_btn_Blue' and @node-type='ok' and @href='javascript:;']"));
            stopAlert.click();
        }

        System.err.println(opStr+":成功");

    }

    /**
     * 去协作
     * */
    private void goXz(WebDriver driver){

        WebElement ele = CookieUtils.wait(driver,By.xpath("//a[@href='#cooperation']"));

        if(ele.isSelected()){
            return;
        }
        ele.click();
    }
    @Override
    public void closeSummaryStep1(String describe) {
        String url = "https://work.weixin.qq.com/wework_admin/setJobSummaryOpen?" +
                "lang=zh_CN&f=json&ajax=1&timeZoneInfo%5Bzone_offset%5D=-8&random="+Math.random();

//        Map<String,Object> params = new HashMap<>();
//        params.put("state",2);
//        params.put("_d2st","a5990576");

        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
        params.add("open[open_job_summary]", false);

        HttpHeaders httpHeaders = new HttpHeaders();

        httpHeaders.put(HttpHeaders.COOKIE, cookie);
        httpHeaders.set("content-type","application/x-www-form-urlencoded");
        httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        httpHeaders.add("Referer","https://work.weixin.qq.com/wework_admin/frame");

        HttpEntity requestEntity = new HttpEntity<>(params, httpHeaders);

        JSONObject json = restTemplate.postForObject(url,requestEntity,JSONObject.class);
        this.print(json,describe);

    }


    @Override
    public void closeSummaryStep2(String describe) {
        String url = "https://work.weixin.qq.com/wework_admin/setJobSummaryOpen?" +
                "lang=zh_CN&f=json&ajax=1&timeZoneInfo%5Bzone_offset%5D=-8&random="+Math.random();

        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
        params.add("open[open_job_summary_leader]", false);


        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.put(HttpHeaders.COOKIE, cookie);
        httpHeaders.set("content-type","application/x-www-form-urlencoded");
        httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        httpHeaders.add("Referer","https://work.weixin.qq.com/wework_admin/frame");

        HttpEntity requestEntity = new HttpEntity<>(params, httpHeaders);

        JSONObject json = restTemplate.postForObject(url,requestEntity,JSONObject.class);
        this.print(json,describe);

    }
    /**
     * 一周小结3
     */
    @Override
    public void closeSummaryStep3(String describe) {
        String url = "https://work.weixin.qq.com/wework_admin/setJobSummaryOpen?" +
                "lang=zh_CN&f=json&ajax=1&timeZoneInfo%5Bzone_offset%5D=-8&random="+Math.random();

        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
        params.add("open[open_job_summary_admin]", false);

        HttpHeaders httpHeaders = new HttpHeaders();

        httpHeaders.put(HttpHeaders.COOKIE, cookie);
        httpHeaders.set("content-type","application/x-www-form-urlencoded");
        httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        httpHeaders.add("Referer","https://work.weixin.qq.com/wework_admin/frame");

        HttpEntity requestEntity = new HttpEntity<>(params, httpHeaders);

        JSONObject json = restTemplate.postForObject(url,requestEntity,JSONObject.class);
        this.print(json,describe);

    }

    /**
     * 一周小结4
     */
    @Override
    public void closeSummaryStep4(String describe) {
        String url = "https://work.weixin.qq.com/wework_admin/setJobSummaryOpen?" +
                "lang=zh_CN&f=json&ajax=1&timeZoneInfo%5Bzone_offset%5D=-8&random="+Math.random();

        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
        params.add("open[open_comic]", false);

        HttpHeaders httpHeaders = new HttpHeaders();

        httpHeaders.put(HttpHeaders.COOKIE, cookie);
        httpHeaders.set("content-type","application/x-www-form-urlencoded");
        httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        httpHeaders.add("Referer","https://work.weixin.qq.com/wework_admin/frame");

        HttpEntity requestEntity = new HttpEntity<>(params, httpHeaders);

        JSONObject json = restTemplate.postForObject(url,requestEntity,JSONObject.class);
        this.print(json,describe);

    }

    /**
     * 关闭红包
     */
    @Override
    public void closeRedPacket(String describe) {
        String url = "https://work.weixin.qq.com/wework_admin/invite/itilHBConfig?" +
                "lang=zh_CN&f=json&ajax=1&timeZoneInfo%5Bzone_offset%5D=-8&optype=3&isenable=0&random="+Math.random();

        Map<String,Object> params = new HashMap<>();

        HttpHeaders httpHeaders = new HttpHeaders();

        httpHeaders.put(HttpHeaders.COOKIE, cookie);
        httpHeaders.set("content-type","application/x-www-form-urlencoded");
        httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        httpHeaders.add("Referer","https://work.weixin.qq.com/wework_admin/frame");

        HttpEntity requestEntity = new HttpEntity<>(httpHeaders);

        ResponseEntity<JSONObject> exchange = restTemplate.exchange(url, HttpMethod.GET, requestEntity, JSONObject.class);

        this.print(exchange.getBody(),describe);
    }


    /**
     * 关闭上下游居民群
     */
    @Override
    public void closeDownstream(String describe) {
        String url = "https://work.weixin.qq.com/wework_admin/customer/followers?" +
                "lang=zh_CN&f=json&ajax=1&timeZoneInfo%5Bzone_offset%5D=-8&random="+Math.random();

        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();

        HttpHeaders httpHeaders = new HttpHeaders();

        httpHeaders.put(HttpHeaders.COOKIE, cookie);
        httpHeaders.set("content-type","application/x-www-form-urlencoded");
        httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        httpHeaders.add("Referer","https://work.weixin.qq.com/wework_admin/frame");

        HttpEntity requestEntity = new HttpEntity<>(params, httpHeaders);

        JSONObject json = restTemplate.postForObject(url,requestEntity,JSONObject.class);
        this.print(json,describe);

    }

    /**
     *关闭政民朋友圈
     */
    @Override
    public void closeMomentsRange(String describe) {
        String url = "https://work.weixin.qq.com/wework_admin/customer/group/setMomentsRange?" +
                "lang=zh_CN&f=json&ajax=1&timeZoneInfo%5Bzone_offset%5D=-8&random="+Math.random();

        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();

        HttpHeaders httpHeaders = new HttpHeaders();


        httpHeaders.put(HttpHeaders.COOKIE, cookie);
        httpHeaders.set("content-type","application/x-www-form-urlencoded");
        httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        httpHeaders.add("Referer","https://work.weixin.qq.com/wework_admin/frame");

        HttpEntity requestEntity = new HttpEntity<>(params, httpHeaders);

        JSONObject json = restTemplate.postForObject(url,requestEntity,JSONObject.class);
        this.print(json,describe);

    }


    /**
     * 设置上下游加入
     */
    @Override
    public void closeUpstream(String describe) {
        String url = "https://work.weixin.qq.com/wework_admin/corpChain/BatchAddChainRange?" +
                "lang=zh_CN&ajax=1&f=json&random=802128"; //+Math.random();

        Map<String,Object> params = new HashMap<>();
        JSONArray jsonArray = this.closeGetCorpChainList();

        if(Objects.isNull(jsonArray)||jsonArray.size()==0){
            System.out.println("success:"+"无需设置上下游加入，管理员审核设置");
            return;
        }

        JSONObject jsont = (JSONObject) jsonArray.get(0);
        JSONObject partyIdList = this.closeGetChainRange(jsont.getString("groupid"));
        this.applySetting(partyIdList.getString("mainparty_id"),"申请加入设置");

        jsonArray.forEach(e -> {
            JSONObject jsonObject = (JSONObject) e;
            String groupid = jsonObject.getString("groupid");
            params.put("groupid",groupid);
            params.put("partyIdList", Arrays.asList(partyIdList.getString("mainparty_id")));
            params.put("vidList",new ArrayList<>());
            HttpHeaders httpHeaders = new HttpHeaders();

            httpHeaders.put(HttpHeaders.COOKIE, cookie);
            httpHeaders.set("content-type","application/json");
            httpHeaders.setContentType(MediaType.APPLICATION_JSON);
            httpHeaders.add("Referer","https://work.weixin.qq.com/wework_admin/frame");

            HttpEntity requestEntity = new HttpEntity<>(params, httpHeaders);

            JSONObject json = restTemplate.postForObject(url,requestEntity,JSONObject.class);
            this.print(json,describe);


        });



    }


    /**
     * 应用管理
     * @param business_id
     */
    @Override
    public void wxkf(String business_id,String describe) {
        String url = "https://work.weixin.qq.com/wework_admin/ModifyCorpApplication?" +
                "lang=zh_CN&f=json&ajax=1&timeZoneInfo%5Bzone_offset%5D=-8&random="+Math.random();

        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
        params.add("business_id", business_id);
        params.add("open_state", 0);
        params.add("app_type", 1);

        HttpHeaders httpHeaders = new HttpHeaders();

        httpHeaders.put(HttpHeaders.COOKIE, cookie);
        httpHeaders.set("content-type","application/x-www-form-urlencoded");
        httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        httpHeaders.add("Referer","https://work.weixin.qq.com/wework_admin/frame");

        HttpEntity requestEntity = new HttpEntity<>(params, httpHeaders);

        JSONObject json = restTemplate.postForObject(url,requestEntity,JSONObject.class);
        this.print(json,describe);

    }


    /**
     * 设置
     */
    @Override
    public void setting(String describe) {
        String url = "https://work.weixin.qq.com/wework_admin/profile/corp/setting?" +
                "lang=zh_CN&f=json&ajax=1&timeZoneInfo%5Bzone_offset%5D=-8&random="+Math.random();

        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
        params.add("offlinemsg_open", false);
        params.add("startup_info[type]", 0);
        params.add("enable_languages", false);
        HttpHeaders httpHeaders = new HttpHeaders();

        httpHeaders.put(HttpHeaders.COOKIE, cookie);
        httpHeaders.set("content-type","application/x-www-form-urlencoded");
        httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        httpHeaders.add("Referer","https://work.weixin.qq.com/wework_admin/frame");

        HttpEntity requestEntity = new HttpEntity<>(params, httpHeaders);

        JSONObject json = restTemplate.postForObject(url,requestEntity,JSONObject.class);
        this.print(json,describe);

    }

    /**
     * 保存插件码
     * */
    @Override
    public void getQrCode(WebDriver driver) {

//        CompletableFuture.runAsync(()->{
//
//        }).exceptionally(e->{
//            System.err.println(e.getMessage());
//            return null;
//        });

        String url = "https://work.weixin.qq.com/wework_admin/wxplugin/getDetail?" +
                "lang=zh_CN&f=json&ajax=1&timeZoneInfo%5Bzone_offset%5D=-8&random="+Math.random();

        HttpHeaders httpHeaders = new HttpHeaders();

        httpHeaders.put(HttpHeaders.COOKIE, cookie);
        httpHeaders.set("content-type","application/x-www-form-urlencoded");
        httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        httpHeaders.add("referer","https://work.weixin.qq.com/wework_admin/frame");
        HttpEntity requestEntity = new HttpEntity<>(null, httpHeaders);


        ResponseEntity<JSONObject> entity = restTemplate.exchange(url,HttpMethod.GET,requestEntity,JSONObject.class);


//
//        System.err.println("获取插件码info"+entity.getBody());

        JSONObject json = this.getJson(driver);
        System.out.println("json解析==>"+json);

        if(entity.getStatusCode().equals(HttpStatus.OK)&& null != entity.getBody()){
            JSONObject result =  entity.getBody().getJSONObject("data");
            String path = result.getString("qrCode");
            System.err.println("获取插件码成功:"+path);
            //保存插件到本地
            if(json != null && StringUtils.isNotBlank(json.getString("corp_alias"))) {
                this.savaImg(path, json);
            }
        }


    }


    private JSONObject getJson(WebDriver driver){

        // 使用JavaScript执行器来获取页面上的JavaScript代码
        JavascriptExecutor jsExecutor = (JavascriptExecutor) driver;
        String jsCode = (String) jsExecutor.executeScript("return document.documentElement.outerHTML");

        // 定义正则表达式模式
        //String regex = "window.settings =\\s*\\{[^}]*\\};";

        //System.out.println(jsCode);

        String regex = "window\\.settings\\s*=\\s*\\{[\\s\\S]*?\\};";

        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(jsCode);

        JSONObject json = new JSONObject();

        while (matcher.find()) {
            String matchedString = matcher.group();
            matchedString = matchedString.replace("window.settings =","").replace(";","");
            json = JSONObject.parseObject(matchedString);
            System.err.println(json);
        }


        return  json;
    }


    private void savaImg(final String imageUrl,JSONObject json){

        try {
            if (!StringUtils.isNotBlank(json.getString("encode_corp_id"))||!StringUtils.isNotBlank(json.getString("corp_alias"))){
                System.err.println(StrUtil.format("设置错误==>corp_id：{}；corp_name：{}",json.getString("encode_corp_id"),json.getString("corp_alias")));
            }else {
                //设置corp_id
                JSONObject jsonObject = this.saveSimpleCorpId("prod", json.getString("encode_corp_id"), json.getString("corp_alias"));
                System.out.println(jsonObject);
            }

            System.out.println("开始保存图片："+imageUrl);

            String fileName = json.getString("corp_alias")+".jpg";
            File file = new File(System.getProperty("user.dir") + "/imgs");
            file.mkdirs();


            System.out.println("图片名称："+fileName);

            URL url = new URL(imageUrl);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            int responseCode = httpURLConnection.getResponseCode();

            if (responseCode == HttpURLConnection.HTTP_OK) {
                InputStream inputStream = httpURLConnection.getInputStream();
                FileOutputStream outputStream = new FileOutputStream(System.getProperty("user.dir") + "/imgs/" +fileName);

                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }

                outputStream.close();
                inputStream.close();
                System.out.println("图片已成功保存到本地");
            } else {
                System.out.println("无法下载图片。响应代码：" + responseCode);
            }
        } catch (IOException e) {
            System.out.println("保存失败：" + e.getMessage());
        }

    }


    /**
     * 申请加入设置
     */
    public void applySetting(String partyid,String describe) {
        String url = "https://work.weixin.qq.com/wework_admin/profile/apply/setting?" +
                "lang=zh_CN&f=json&ajax=1&timeZoneInfo%5Bzone_offset%5D=-8&random="+Math.random();

        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
        params.add("isaccepted", true);
        params.add("join_need_verify", false);
        params.add("b_join_by_corp_name", true);
        params.add("open", false);
        params.add("remark", "填写申请加入理由");
        params.add("invite_join_partyid", partyid);

        HttpHeaders httpHeaders = new HttpHeaders();


        httpHeaders.put(HttpHeaders.COOKIE, cookie);
        httpHeaders.set("content-type","application/x-www-form-urlencoded");
        httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        httpHeaders.add("Referer","https://work.weixin.qq.com/wework_admin/frame");

        HttpEntity requestEntity = new HttpEntity<>(params, httpHeaders);

        JSONObject json = restTemplate.postForObject(url,requestEntity,JSONObject.class);
        this.print(json,describe);

    }


    public JSONArray closeGetCorpChainList() {
        String url = "https://work.weixin.qq.com/wework_admin/corpChain/getCorpChainList?" +
                "lang=zh_CN&ajax=1&f=json&random="+Math.random();

        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();

        HttpHeaders httpHeaders = new HttpHeaders();


        httpHeaders.put(HttpHeaders.COOKIE, cookie);
        httpHeaders.set("content-type","application/x-www-form-urlencoded");
        httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        httpHeaders.add("Referer","https://work.weixin.qq.com/wework_admin/frame");

        HttpEntity requestEntity = new HttpEntity<>(params, httpHeaders);

        JSONObject json = restTemplate.postForObject(url,requestEntity,JSONObject.class);
        JSONArray jsonArray = new JSONArray();
        if(json.containsKey("data")){
            System.out.println("微信插件：获取信息成功");
            JSONObject data = json.getJSONObject("data");
            JSONArray memberCorpChainList = data.getJSONArray("memberCorpChainList");
            JSONArray o = memberCorpChainList;
            // String groupid = o.getString("groupid");
            return o;
        }
        return jsonArray;
    }

    public JSONObject closeGetChainRange(String groupid) {
        String url = "https://work.weixin.qq.com/wework_admin/corpChain/GetChainRange?" +
                "lang=zh_CN&ajax=1&f=json&random="+Math.random();

        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
        params.add("groupid", groupid);
        HttpHeaders httpHeaders = new HttpHeaders();

        httpHeaders.put(HttpHeaders.COOKIE, cookie);
        httpHeaders.set("content-type","application/x-www-form-urlencoded");
        httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        httpHeaders.add("Referer","https://work.weixin.qq.com/wework_admin/frame");

        HttpEntity requestEntity = new HttpEntity<>(params, httpHeaders);

        JSONObject json = restTemplate.postForObject(url,requestEntity,JSONObject.class);
        if(json.containsKey("data")){
            System.out.println("微信插件：获取信息成功");
            JSONObject data = json.getJSONObject("data");
            JSONArray memberCorpChainList = data.getJSONArray("members");
            JSONObject o = (JSONObject) memberCorpChainList.get(0);
            // String groupid = o.getString("mainparty_id");
            return o;
        }
        return json;
    }

    public void print(JSONObject json,String describe){
        if (null == json){
            System.err.println(describe+"：中返回结果为空");
            return;
        }
        if(json.containsKey("data")){
            System.out.println("success:"+describe);
        }else {
            System.err.println("error:"+describe+"======>>>错误:"+json);
        }
    }


    @Override
    public JSONObject saveSimpleCorpId(String env,String corp_id, String corp_name) {

        String path="admin/saveSimpleCorpId";
        String url = "http://tmp.s.weshaketv.com/cnag_hb_api";
        if ("prod".equals(env)){
            url = "https://mp.s.weshaketv.com/cnag_hb_api";
        }
        url = StrUtil.format("{}/{}",url,path);
        JSONObject object = new JSONObject();
        object.put("corp_id",corp_id);
        object.put("corp_name",corp_name);

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity requestEntity = new HttpEntity<>(object,httpHeaders);
        return restTemplate.postForObject(url,requestEntity,JSONObject.class);

        //return restTemplate.postForObject(url, object, JSONObject.class);
    }
}
